package cn.lzb.book.server.service.impl;

import cn.lzb.book.server.common.exception.BaseExceptionEnums;
import cn.lzb.book.server.common.exception.BookServerException;
import cn.lzb.book.server.component.CategoryHelper;
import cn.lzb.book.server.dao.po.CategoryPo;
import cn.lzb.book.server.dao.repository.CategoryRepository;
import cn.lzb.book.server.entity.vo.CategoryVo;
import cn.lzb.book.server.service.ICategoryService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author liuzhibo
 * @date 2024/8/28 16:59
 **/
@RequiredArgsConstructor
@Service
public class CategoryServiceImpl implements ICategoryService {

    private final CategoryRepository categoryRepository;

    @Override
    public CategoryVo queryCategory(String categoryCode) {
        List<CategoryPo> categoryPos = categoryRepository.queryCategory(categoryCode);
        if (CollectionUtils.isEmpty(categoryPos)) {
            throw new BookServerException(BaseExceptionEnums.Common.DATA_MISS);
        }
        CategoryPo root = categoryPos.stream()
                .filter(elm -> StringUtils.equalsIgnoreCase(elm.getCode(), categoryCode))
                .findAny().orElseThrow(() -> new BookServerException(BaseExceptionEnums.Common.DATA_MISS));
        List<CategoryVo> categoryVos = CategoryHelper.categoryPo2Tree(categoryPos, root);
        return categoryVos.get(0);
    }

    @Override
    public List<CategoryVo> queryAllCategory() {
        List<CategoryPo> categoryPos = categoryRepository.queryAllCategory();
        return CategoryHelper.categoryPo2Tree(categoryPos);
    }
}
